//
//  MyAttendanceViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 17/1/2.
//  Copyright © 2017年 com.xtion.crm. All rights reserved.
//

#import "MyAttendanceViewController.h"
#import "AttendanceListCell.h"
#import "AddAttendanceViewController.h"

NSString *const MyAttendanceViewControllerTitleParamKey = @"MyAttendanceViewControllerTitleParamKey";

@interface MyAttendanceViewController ()
{
    RSWDataOperation *_manager;
    
    NSDate *_lastUpdatetime;
    BOOL _bSearching;
    
    EmptyTipView *_emptyTipView;
    
    NSInteger _pageSize;
    NSInteger _pageIndex;
    
    NSMutableArray *_datas;
    NSMutableArray *_searchDatas;
}
@end

@implementation MyAttendanceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkSession];
    
    NSString *title = self.param[MyAttendanceViewControllerTitleParamKey];
    [self setBackNavigateItemTitle:title  rightItemImageName:@"nav_btn_add"];
    
    self.view.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color];
    
    [self initVariable];
    [self initUI];
    
    [_manager getMyAttendance:_pageIndex pageSize:_pageSize completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         _bRefreshing = NO;
         
         [self requestComplete:nil funcationName:@"getMyAttendance" result:nResult output:list error:error];
     }];
}

- (void)initVariable
{
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    _searchDatas = [NSMutableArray new];
    _datas = [NSMutableArray new];
    
    _lastUpdatetime = [NSDate date];
    _pageIndex = 1;
    _pageSize = 20;
    
    [self addMainThreadObserverWithDictionarySelector:@{RSWDataOperationAttendanceAddNotification:
                                                            @"observerRSWDataOperationAttendanceAddNotification:"
                                                        }];
}

- (void)initUI
{
    [self createTableView:XUITabelViewStyleTypePlain|XUITabelViewStyleTypeRefresh];
    _ctable.separatorExistFollowCell = YES;
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    [_manager terminateRequest];
    [self removeObserver];
}

-(NSMutableArray*)attendanceData;
{
    if(_bSearching == YES)
        return _searchDatas;
    
    return _datas;
}

-(void)requestComplete:(XMSDataOperationManager *)dom funcationName:(NSString *)szFuncationname result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    _bRefreshing = NO ;
    
    if([szFuncationname isEqualToString:@"getMyAttendance"])
    {
        [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
         {
             switch(requestResult)
             {
                 case YES:
                 {
                     [_datas removeAllObjects];
                     
                     NSArray *ar = output;
                     ar = [self insertEmptyWithOriginArray:_datas newArray:ar];
                     
                     [_datas addObjectsFromArray:ar];
                     
                     if(_datas.count >= _pageSize)
                         [_ctable createLoadMoreView];
                     else
                         [_ctable removeLoadMoreView];
                     
                     [_ctable reloadData];
                     
                     break;
                 }
                 default:
                 {
                     [UIAlertView showErrorMsg:@"数据请求失败"];
                     break;
                 }
             }
         }];
    }
    else if([szFuncationname isEqualToString:@"getMyAttendanceMore"])
    {
        [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
         {
             switch(requestResult)
             {
                 case YES:
                 {
                     if(((NSArray*)output).count > 0)
                     {
                         NSArray *ar = output;
                         
                         ar = [self insertEmptyWithOriginArray:_datas newArray:ar];
                         
                         [_datas removeAllObjects];
                         [_datas addObjectsFromArray:ar];
                         
                         [_ctable reloadData];
                     }
                     else
                         [_ctable removeLoadMoreView];
                     
                     break;
                 }
                 default:
                 {
                     [UIAlertView showErrorMsg:@"数据获取失败"];
                     break;
                 }
             }
         }];
    }
}

-(NSArray*)insertEmptyWithOriginArray:(NSArray*)oriArray newArray:(NSArray*)newArray
{
    NSMutableArray *ar = [NSMutableArray arrayWithArray:oriArray];
    
    for(NSUInteger i = 0 ; i < newArray.count ; i++)
    {
        AttendanceList *newL = newArray[i];
        
        if(i > 0)
        {
            AttendanceList * dtl = [AttendanceList new];
            dtl.type = AttendanceListEmpty;
            [ar addObject:dtl];
        }
        
        {
            AttendanceList * dtl = [AttendanceList new];
            dtl = newL;
            dtl.type = AttendanceListContent;
            
            [ar addObject:dtl];
        }
    }
    
    return ar;
}

#pragma mark --
#pragma mark -- tableView delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AttendanceList * l = _datas[indexPath.row];
    if(l.rowHeight <= CaleRowHeightTag)
    {
        switch(l.type)
        {
            case AttendanceListEmpty:
            {
                l.rowHeight = [EmptyCell caleHeight];
                break;
            }
            case AttendanceListContent:
            {
                l.rowHeight = [AttendanceListCell caleHeight:tableView.width content:l.content];
                break;
            }
            default:
            {
                break;
            }
        }
    }
    return l.rowHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self attendanceData].count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AttendanceList * l = _datas[indexPath.row];
    switch(l.type)
    {
        case AttendanceListEmpty:
        {
            EmptyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EmptyCell"];
            if(cell == nil)
                cell = [[EmptyCell alloc]initWithReuseIdentifier:@"EmptyCell"];
            return cell;
            
            break;
        }
        case AttendanceListContent:
        {
            AttendanceListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AttendanceListContent"];
            if(cell == nil)
            {
                cell = [[AttendanceListCell alloc]initWithReuseIdentifier:@"AttendanceListContent"];
            }
            
            AttendanceList *bi = [self attendanceData][indexPath.row];
            
            cell.szTag = bi.attendanceId;
            
            cell.title = bi.title;
            cell.content = bi.content;
            cell.createTime =  bi.createTime;
                                
            return cell;
            
            break;
        }
        default:
        {
            break;
        }
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    [UIViewController closeKeyBoard];
}

-(id)contentLastRefreshUpdateTimeOfTableView:(XUITableView *)tableview
{
    return _lastUpdatetime;
}

-(void)tableView:(XUITableView *)tableview refreshTableContent:(void (^)())asyncEndRefreshing
{
    if(_bRefreshing == YES)
        return;
    
    _bRefreshing = YES;
    [_manager stopRequest];
    
    _pageIndex = 1;
    [_manager getMyAttendance:_pageIndex pageSize:_pageSize completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         if(nResult == YES)
             _lastUpdatetime = [NSDate date];
         
         _bRefreshing = NO;
         
         [self requestComplete:nil funcationName:@"getMyAttendance" result:nResult output:list error:error];
     }];
}

#pragma mark --
#pragma mark -- loadMore delegate

- (void)loadMoreContentOfTableView:(XUITableView *)tableview
{
    if(_bLoadmoring == YES)
        return;
    
    if([_ctable.searchBar.searchText isEqualToString:@""] == NO)
    {
        _ctable.searchBar.searchText = @"";
        _bSearching = NO;
        [_searchDatas  removeAllObjects];
        [_ctable reloadData];
    }
    
    _bLoadmoring = YES;
    
    [tableview showLoadMoreStatus];
    
    _pageIndex ++;
    
    [_manager getMyAttendance:_pageIndex pageSize:_pageSize completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         [tableview hideLoadMoreStatus];
         
         _bLoadmoring = NO;
         
         [self requestComplete:nil funcationName:@"getMyAttendanceMore" result:nResult output:list error:error];
     }];
}

- (void)tableView:(XUITableView *)tableview didClickedLoadMoreFootView:(XUILoadMoreFootView *)sender
{
    [self loadMoreContentOfTableView:tableview];
}

#pragma mark --
#pragma mark -- observer

-(void)observerRSWDataOperationAttendanceAddNotification:(NSNotification*)noti
{
    
}

-(void)clickedRightBarButton:(id)sender
{
    [XUINavigationController pushViewControllerClass:[AddAttendanceViewController class]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
